<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="showResult = false"
        class="search-box"
        clearable
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <SearchResult v-if="showResult" :search-text="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <SearchSuggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 历史记录 -->
    <SearchHistory
      v-else
      :search-history="searchHistory"
      @deleteAllHistory="deleteAllHistory"
      @deleteHistory="deleteHistory"
      @search="onSearch"
    />
    <!-- /历史记录 -->
  </div>
</template>

<script>
import SearchSuggestion from "./components/search-suggestion";
import SearchHistory from "./components/search-history";
import SearchResult from "./components/search-result";

import { setItem, getItem } from "@/utils/storage";

export default {
  name: "Search",
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResult,
  },
  data() {
    return {
      searchText: "", // 搜索框的内容
      showResult: false, // 是否展示搜索结果
      searchHistory: getItem("search-history") || [], // 搜索历史记录
    };
  },
  watch: {
    searchHistory(newVal) {
      setItem("search-history", newVal);
    },
  },
  methods: {
    // 搜索时触发
    onSearch(searchText) {
      this.searchText = searchText;
      const index = this.searchHistory.indexOf(searchText);
      if (index !== -1) {
        this.searchHistory.splice(index, 1);
      }
      this.searchHistory.unshift(searchText);

      this.showResult = true;
    },
    // 删除全部搜索历史
    deleteAllHistory() {
      this.searchHistory = [];
    },
    // 删除某一个搜索历史
    deleteHistory(index) {
      this.searchHistory.splice(index, 1);
    },
  },
};
</script>

<style scoped lang="less">
.search-result {
  position: fixed;
  left: 0;
  right: 0;
  top: 62px;
  bottom: 0;
  overflow-y: auto;
}

.search-box {
  padding: 26px 18px 8px 15px;
  background-color: #3296fa;

  .van-search__content {
    height: 28px;
    border-radius: 3px;

    /deep/.van-field__left-icon {
      line-height: 18px;
    }

    /deep/ .van-field__body {
      line-height: 18px;
    }
  }

  .van-search__action {
    width: 35px;
    height: 28px;
    padding: 0;
    margin-left: 15px;
    text-align: right;
    font-size: 14px;
    color: #fff;
    line-height: 28px;
  }
}
</style>
